package com.dw.widget.slideshow.config;

import java.util.List;


import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.dw.widget.slideshow.config.view.list.BaseListItemView;
import com.dw.widget.slideshow.config.view.list.ListBlockView;
import com.dw.widget.slideshow.config.view.list.ListGapItemView;
import com.dw.widget.slideshow.config.view.list.ListNextItemView;
import com.dw.widget.slideshow.config.view.list.ListSwitchItemView;
import com.dw.widget.slideshow.config.view.list.ListSwitchItemView.OnToggleSwitchListener;
import com.dw.widget.slideshow.db.helper.ImageDBHelper;
import com.dw.widget.slideshow.db.helper.ScanFolderHelper;
import com.dw.widget.slideshow.db.object.ImageData;
import com.dw.widget.slideshow.db.object.ScanFolderData;
import com.dw.widget.slideshow.launcher.WidgetProvider;
import com.dw.widget.slideshow.utils.AppCommon;
import com.dw.widget.slideshow.utils.AppConfig;
import com.dw.widget.slideshow.utils.ApplicationEx;
import com.dw.widget.slideshow.utils.CommonUtils;
import com.dw.widget.slideshow.utils.db.DataObject;
import com.dw.widget.slideshow.utils.log.Log;
import com.dw.widget.slideshow.R;

public class ConfigMainActivity extends Activity implements OnItemClickListener{

	private int mAppWidgetId;
	
	private ListBlockView settingBlock;
	
	private Button bnOk;
	
	private final ApplicationEx _APP = ApplicationEx.INSTANCE();
	private final String TAG = "ConfigMainActivity";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	Log.d(this, TAG, "ConfigMainActivity onCreate");
        super.onCreate(savedInstanceState);
        
        initAppSettings();
        
        setContentView(R.layout.config_main);
        findViewsById();
        initViews();
        
        //////////////////////////////////////////////////////////
        setResult(RESULT_CANCELED);  
        
        // Find the widget id from the intent.  
        Intent intent = getIntent();  
        Bundle extras = intent.getExtras();  
        if (extras != null) {  
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);  
        }  
  
        // If they gave us an intent without the widget id, just fail.  
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {  
            finish();  
        }  
          
        
        //////////////////////////////////////////////////////////
        
        // 是否安装专业版
        _APP.isProfessional = AppCommon.isProfessionalEdition();
    }
    
    private void findViewsById()
    {
    	settingBlock = (ListBlockView)findViewById(R.id.configmain_block);
    	bnOk = (Button)findViewById(R.id.configmain_bnOk);
    }
    
    private void initViews()
    {

        final AppConfig appConfig = new AppConfig(ConfigMainActivity.this, _APP.CONFIG_FILE_NAME);
    	
    	// 设置区域1
    	ListSwitchItemView cameraToggleItem = (ListSwitchItemView) LayoutInflater.from(this).inflate(R.layout.listitem_switch, null);
    	cameraToggleItem.ItemType = BaseListItemView.BLOCKHEADERITEM;
    	cameraToggleItem.setBackgroundColor(0xFF0CADB7);
    	setItemFontStyle(cameraToggleItem.getTextView());
    	cameraToggleItem.setText(getString(R.string.camera_config_tip));
    	cameraToggleItem.setIcon(R.drawable.icon_line01);
    	cameraToggleItem.setOnToggleSwitchListener(new OnToggleSwitchListener() {
			
			@Override
			public void onSwitch(boolean on) {
				
				ScanFolderHelper dbHelper = new ScanFolderHelper(ConfigMainActivity.this, _APP.DB_NAME, ScanFolderData.class);
				
				ScanFolderData data = new ScanFolderData();
				data.setFolder(_APP.IMAGE_DIR);
				data.setSource(_APP.SOURCE_CAMERA);
				if(on)
				{
					Log.d(ConfigMainActivity.this, TAG, "add Camera folder");
					
					// add if not exist
					List<DataObject> fs = dbHelper.query(data);
					if(fs == null || fs.size() <= 0)
					{
						data.setScaned(_APP.NO);
						dbHelper.insert(data);
					}
				}
				else
				{
					// delete folder
					dbHelper.delete(data);
					
					// delete files
					ImageDBHelper imageDbHelper = new ImageDBHelper(ConfigMainActivity.this, _APP.DB_NAME, ImageData.class);
					String sql = String.format("DELETE FROM %1$s WHERE folder LIKE '%2$s%%'", 
								imageDbHelper.getTableName(), _APP.IMAGE_DIR);
					
					Log.d(ConfigMainActivity.this, TAG, String.format("delete sql: %1$s", sql));
					imageDbHelper.getWritableDatabase().execSQL(sql);
					imageDbHelper.getWritableDatabase().close();
				}
				
				appConfig.putBoolean(_APP.CONFIG_ITEM_CAMERA, on);
			}
		});
    	
    	boolean cameraEnabled = appConfig.getBoolean(_APP.CONFIG_ITEM_CAMERA);
    	cameraToggleItem.getToggle().setChecked(cameraEnabled);
    	
    	settingBlock.addListItem(cameraToggleItem);
    	
    	ListNextItemView chooseFoldersItem = (ListNextItemView) LayoutInflater.from(this).inflate(R.layout.listitem_next, null);
    	chooseFoldersItem.setBackgroundResource(R.drawable.setting_folder_list_bg);
    	setItemFontStyle(chooseFoldersItem.getTextView());
    	chooseFoldersItem.setText(getString(R.string.choosefolder_tip));
    	chooseFoldersItem.setIcon(R.drawable.icon_line02);
    	settingBlock.addListItem(chooseFoldersItem);
    	
    	final ListSwitchItemView flickrToggleItem = (ListSwitchItemView) LayoutInflater.from(this).inflate(R.layout.listitem_switch, null);
    	flickrToggleItem.ItemType = BaseListItemView.BLOCKFOOTERITEM;
    	flickrToggleItem.setBackgroundColor(0xFFFF0084);
    	setItemFontStyle(flickrToggleItem.getTextView());
    	flickrToggleItem.setText(getString(R.string.flickr_interestingness));
    	flickrToggleItem.setIcon(R.drawable.icon_line03);
    	flickrToggleItem.setOnToggleSwitchListener(new OnToggleSwitchListener() {
			
			@Override
			public void onSwitch(boolean on) {
				
				CommonUtils.showShortToast(ConfigMainActivity.this, ConfigMainActivity.this.getString(R.string.coming_soon));
				flickrToggleItem.getToggle().setChecked(false);
				
				//appConfig.putBoolean(_APP.CONFIG_ITEM_FLICKR, on);
			}
		});
    	//settingBlock.addListItem(flickrToggleItem);
    	
    	ListGapItemView gapItem1 = (ListGapItemView) LayoutInflater.from(this).inflate(R.layout.listitem_gap, null);
    	settingBlock.addListItem(gapItem1);
    	
    	// 设置区域2
    	ListNextItemView chooseThemeItem = (ListNextItemView) LayoutInflater.from(this).inflate(R.layout.listitem_next, null);
    	chooseThemeItem.ItemType = BaseListItemView.BLOCKHEADERITEM;
    	chooseThemeItem.setBackgroundResource(R.drawable.setting_frame_list_bg);
    	setItemFontStyle(chooseThemeItem.getTextView());
    	chooseThemeItem.setText(getString(R.string.choose_style_tip));
    	chooseThemeItem.setIcon(R.drawable.icon_line04);
    	settingBlock.addListItem(chooseThemeItem);
    	
    	ListNextItemView chooseAnimationItem = (ListNextItemView) LayoutInflater.from(this).inflate(R.layout.listitem_next, null);
    	chooseAnimationItem.ItemType = BaseListItemView.BLOCKFOOTERITEM;
    	chooseAnimationItem.setBackgroundResource(R.drawable.setting_animation_list_bg);
    	setItemFontStyle(chooseAnimationItem.getTextView());
    	chooseAnimationItem.setText(getString(R.string.choose_animation_tip));
    	chooseAnimationItem.setIcon(R.drawable.icon_line05);
    	settingBlock.addListItem(chooseAnimationItem);
    	
    	ListGapItemView gapItem2 = (ListGapItemView) LayoutInflater.from(this).inflate(R.layout.listitem_gap, null);
    	settingBlock.addListItem(gapItem2);
    	
    	// 设置区域3
    	ListNextItemView beProfessionalItem = (ListNextItemView) LayoutInflater.from(this).inflate(R.layout.listitem_next, null);
    	beProfessionalItem.ItemType = BaseListItemView.BLOCKHEADFOOTITEM;
    	beProfessionalItem.setBackgroundResource(R.drawable.setting_professional_list_bg);
    	setItemFontStyle(beProfessionalItem.getTextView());
    	
    	String proInfo = _APP.isProfessional ? getString(R.string.professional_user) : getString(R.string.become_professional);
    	beProfessionalItem.setText(proInfo);
    	
    	beProfessionalItem.setIcon(R.drawable.icon_line06);
    	settingBlock.addListItem(beProfessionalItem);
    	
    	settingBlock.setOnItemClickListener(this);
    	
    	bnOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

		        // 设置配置完成标志位
		        appConfig.putBoolean(_APP.CONFIGURATION_DONE, true);
		        
		        // return OK  
		        Intent resultValue = new Intent();  
		        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);  
		          
		        setResult(RESULT_OK, resultValue);
		        finish();

		        // 启动控件
		        updateWidget();
			}
		});
    }
    
    private void setItemFontStyle(TextView tv)
    {
    	tv.setTextColor(0xFFFFFFFF);
    	tv.setTextSize(20.0f);
    }
    
    private void updateWidget()
    {
    	Intent intent = new Intent(this, WidgetProvider.class);
    	intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
    	
    	// Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID,
    	// since it seems the onUpdate() is only fired on that:
    	int[] ids = {mAppWidgetId};
    	intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
    	sendBroadcast(intent);
    }

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		Log.d(this, TAG, String.format("onItemClick arg2 = %1$d", arg2));
		
		if(settingBlock == arg0)
		{
			switch(arg2)
			{
				case 0:
				{
					break;
				}
				case 1:    // 选择图片文件夹
				{
					Intent intent = new Intent(this, FolderListActivity.class);
					startActivity(intent);
					break;
				}
				/*case 2:   // flickr精选
				{
					break;
				}*/
				case 2:   // 分割
				{
					break;
				}
				case 3:   // 选择主题
				{
					Intent intent = new Intent(this, FrameChooserActivity.class);
					startActivity(intent);
					break;
				}
				case 4:   // 切换动画
				{
					Intent intent = new Intent(this, AnimationChooserActivity.class);
					startActivity(intent);
					break;
				}
				case 5:   // 分割
				{
					break;
				}
				case 6:    // 成为专业版
				{
					if(_APP.isProfessional == false)
					{
						AppCommon.installProfessionalEdition(this);
					}
					else
					{
						CommonUtils.showShortToast(this, getString(R.string.thanks));
					}
					
					break;
				}
			}
		}
	}
	
	private void initAppSettings()
	{
		// 初始化数据库
		AppConfig appConfig = new AppConfig(this, _APP.CONFIG_FILE_NAME);
		Boolean initRun = appConfig.getBoolean(_APP.FIRST_INIT_RUN, true);
		if(initRun)   // 首次运行
		{
			Log.d(this, TAG, "init App settings");
			ScanFolderHelper dbHelper = new ScanFolderHelper(this, _APP.DB_NAME, ScanFolderData.class);
			
			// 默认打开相机的图片
			ScanFolderData data = new ScanFolderData();
			data.setFolder(_APP.IMAGE_DIR);
			data.setSource(_APP.SOURCE_CAMERA);
			data.setScaned(_APP.NO);
			dbHelper.insert(data);
			
			appConfig.putBoolean(_APP.CONFIG_ITEM_CAMERA, true);
		}
		
		appConfig.putBoolean(_APP.FIRST_INIT_RUN, false);
	}
}